﻿// <copyright>
// Project: sofort.NET
// Date:  2014 - 02 - 04
// Copyright: Karl Haak 2014
// </copyright>
// <author>Karl Haak (www.karlhaak.de)</author>
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using pay.sofort.Models.Mapping;

namespace pay.sofort.Models
{
    public class PaySofortContext : DbContext
    {
        public PaySofortContext(string connectionString, string username)
            : base(connectionString)
        {
            Username = username;
        }

        private string Username { get; set; }

        public DbSet<PaySofortIn> PaySofortIn { get; set; }
        public DbSet<PaySofortMultipay> PaySofortMultipay { get; set; }
        public DbSet<PaySofortNewTransaction> PaySofortNewTransaction { get; set; }
        public DbSet<PaySofortOut> PaySofortOut { get; set; }
        public DbSet<PaySofortStatusNotfication> PaySofortStatusNotfication { get; set; }
        public DbSet<PaySofortTransaction> PaySofortTransaction { get; set; }
        public DbSet<PaySofortTransactionRequest> PaySofortTransactionRequest { get; set; }

        public override int SaveChanges()
        {
            foreach (
                DbEntityEntry ent in
                    ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Modified))
            {
                var paySofortEntity = ent.Entity as PaySofortBase;
                if (paySofortEntity != null)
                {
                    if (ent.State == EntityState.Added)
                    {
                        paySofortEntity.CreatedAt = DateTime.Now;
                        paySofortEntity.CreatedBy = Username;
                    }
                    if (ent.State == EntityState.Modified)
                    {
                        paySofortEntity.ChangedAt = DateTime.Now;
                        paySofortEntity.CreatedBy = Username;
                    }
                }
            }
            return base.SaveChanges();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new PaySofortInMap());
            modelBuilder.Configurations.Add(new PaySofortMultipayMap());
            modelBuilder.Configurations.Add(new PaySofortNewTransactionMap());
            modelBuilder.Configurations.Add(new PaySofortOutMap());
            modelBuilder.Configurations.Add(new PaySofortStatusNotficationMap());
            modelBuilder.Configurations.Add(new PaySofortTransactionMap());
            modelBuilder.Configurations.Add(new PaySofortTransactionRequestMap());
        }
    }
}